#include "SymbolTablePool.h"

SymbolTablePool * SymbolTablePool::s_pInstance = NULL;

SymbolTablePool::SymbolTablePool(void)
{
	m_pCurrentTable = new SymbolTablePair();
	m_pCurrentTable->pParent = NULL;
	m_pCurrentTable->pSymbolTable = new SymbolTable();
}


SymbolTablePool::~SymbolTablePool(void)
{
	SymbolTablePair *pNext = m_pCurrentTable->pParent;
	delete m_pCurrentTable->pSymbolTable;
	delete m_pCurrentTable;
	while(pNext)
	{
		m_pCurrentTable = pNext;
		pNext = m_pCurrentTable->pParent;

		delete m_pCurrentTable->pSymbolTable;
		delete m_pCurrentTable;
	}
}

SymbolTablePool & SymbolTablePool::getInstance()
{
	if(s_pInstance)
		s_pInstance = new SymbolTablePool();
	return * s_pInstance;
}

SymbolBase * SymbolTablePool::findSymbol( const std::string & strSymbolName ) const
{
	SymbolTablePair *pCur = m_pCurrentTable;
	SymbolBase *pRes = NULL;
	while(pCur)
	{
		pRes = pCur->pSymbolTable->findSymbol(strSymbolName);
		if(pRes)
			return pRes;
		pCur = pCur->pParent;
	}
	return NULL;
}

void SymbolTablePool::addSymbol( SymbolBase *pSymbol )
{
	m_pCurrentTable->pSymbolTable->addSymbol(pSymbol);
}

void SymbolTablePool::enterNewSymbolTable()
{
	SymbolTablePair *pCur = m_pCurrentTable;

	m_pCurrentTable = new SymbolTablePair();
	m_pCurrentTable->pParent = pCur;
	m_pCurrentTable->pSymbolTable = new SymbolTable();
}

void SymbolTablePool::quitCurrentSymbolTable()
{
	SymbolTablePair *pCur = m_pCurrentTable;

	m_pCurrentTable = pCur->pParent;

	delete pCur->pSymbolTable;
	delete pCur;
}